package me.landery.modules.sinco.rest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.landery.annotation.AnonymousAccess;
import me.landery.annotation.Log;
import me.landery.modules.sinco.domain.News;
import me.landery.modules.sinco.service.NewsService;
import me.landery.modules.sinco.service.dto.NewsQueryCriteria;
import me.landery.modules.system.domain.User;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author cc.w
 * @Date 2022/6/15 14:42
 * @Version 1.0
 */
@RestController
@RequiredArgsConstructor
@Api(tags = "Sinco：新闻管理")
@RequestMapping("/sinco/news")
public class NewsController {

    private final NewsService newsService;
    private static final String ENTITY_NAME = "news";

    @ApiOperation("获取全部新闻")
    @AnonymousAccess
    @GetMapping
//    @PreAuthorize("@el.check('news:list','admin')")
    public ResponseEntity<Object> queryNews(NewsQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(newsService.queryAll(criteria, pageable), HttpStatus.OK);
    }

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('news:list','admin')")
    public void exportNews(HttpServletResponse response, NewsQueryCriteria criteria) throws IOException {
        newsService.download(newsService.queryAll(criteria), response);
    }

    @Log("新增新闻")
    @ApiOperation("新增新闻")
    @PostMapping
    @PreAuthorize("@el.check('news:add','admin')")
    public ResponseEntity<Object> createNews(@Validated @RequestBody News resources){
        newsService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改新闻动态")
    @ApiOperation("修改新闻动态")
    @PreAuthorize("@el.check('news:edit','admin')")
    public ResponseEntity<Object> updateNews(@Validated @RequestBody News resources){
        newsService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除新闻动态")
    @ApiOperation("删除新闻动态")
    @PreAuthorize("@el.check('news:del','admin')")
    public ResponseEntity<Object> deleteNews(@RequestBody Long[] ids) {
        newsService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
